# encoding:utf-8
from __future__ import unicode_literals
from django.test import TestCase
from django.test import Client
import json
from models import CarWashLocalModel,MealModel,User,CustomerModel,WXOrderModel,ZKOtherLog,ZKWashLog,WashSessionModel,OrderModel,UserCarModel,\
     CarBrandModel,CarModelModel
import xmltodict
import sms
import urllib
import urlparse
from ex import redis_conn
# Create your tests here.

class TestPay(TestCase):
    def setUp(self):
        user = User.objects.create(username='heyulin')
        
        CustomerModel.objects.create(user=user,openid='oIvmdwi8HWePf8rXFDA-jOpQL5uE')
        car=UserCarModel.objects.create(car_no='川A6666',user=user)
        self.meal = MealModel.objects.create(name='single',label='单次洗车',org_price='10000',price='1',\
                                status='active',priority='100') 
        
        
    
    #def test_wx_pay(self):
               
        #cl=Client(enforce_csrf_checks=True)
        #resp = cl.get('/wxpay/new_order/?pay_type=jsapi&meal=single&openid=oIvmdwi8HWePf8rXFDA-jOpQL5uE')
        #print(resp.content)
    
    def test_reply(self):
        WXOrderModel.objects.create(no='1409811653',meal=self.meal,total_fee=self.meal.price)
        xml="""<xml>
  <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
  <attach><![CDATA[支付测试]]></attach>
  <bank_type><![CDATA[CFT]]></bank_type>
  <fee_type><![CDATA[CNY]]></fee_type>
  <is_subscribe><![CDATA[Y]]></is_subscribe>
  <mch_id><![CDATA[10000100]]></mch_id>
  <nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
  <openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
  <out_trade_no><![CDATA[1409811653]]></out_trade_no>
  <result_code><![CDATA[SUCCESS]]></result_code>
  <return_code><![CDATA[SUCCESS]]></return_code>
  <sign><![CDATA[A7EA9891B0FA85B3F96AEC0225CE9681]]></sign>
  <sub_mch_id><![CDATA[10000100]]></sub_mch_id>
  <time_end><![CDATA[20140903131540]]></time_end>
  <total_fee>1</total_fee>
  <trade_type><![CDATA[JSAPI]]></trade_type>
  <transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
</xml>
        """
        cl=Client(enforce_csrf_checks=True)
        resp = cl.post('/wxpay/notify/',data=xml,content_type='text/xml')
        print(resp.content)
    
    def test_free_car_reply(self):
        cl=Client(enforce_csrf_checks=True)
        cl.get('/car/anonymous_regist?chepai=川A33333')
        car=UserCarModel.objects.get(car_no='川A33333')
        WXOrderModel.objects.create(no='1409811653',meal=self.meal,total_fee=self.meal.price,car=car)
        xml="""<xml>
  <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
  <attach><![CDATA[支付测试]]></attach>
  <bank_type><![CDATA[CFT]]></bank_type>
  <fee_type><![CDATA[CNY]]></fee_type>
  <is_subscribe><![CDATA[Y]]></is_subscribe>
  <mch_id><![CDATA[10000100]]></mch_id>
  <nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
  <openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
  <out_trade_no><![CDATA[1409811653]]></out_trade_no>
  <result_code><![CDATA[SUCCESS]]></result_code>
  <return_code><![CDATA[SUCCESS]]></return_code>
  <sign><![CDATA[A7EA9891B0FA85B3F96AEC0225CE9681]]></sign>
  <sub_mch_id><![CDATA[10000100]]></sub_mch_id>
  <time_end><![CDATA[20140903131540]]></time_end>
  <total_fee>1</total_fee>
  <trade_type><![CDATA[JSAPI]]></trade_type>
  <transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
</xml>
        """
        
        resp = cl.post('/wxpay/notify/',data=xml,content_type='text/xml')
        print(resp.content)    
        

class TestUser(TestCase):
    def setUp(self):
        cl=Client(enforce_csrf_checks=True)
        CarBrandModel.objects.create(name='xxx')
        CarModelModel.objects.create(name='xxx')
        data={
            'mobile':'17138080650',
            'car_no':'川A1234',
            'nick':'我的昵称',
            'car_brand':'1',
            'car_model':'1',
            'passwd':'xxx',
            'openid':'xxx',
        }
        self.data=data
        resp = cl.post('/user/regist',data=json.dumps(data),content_type='application/json')
        self.assertEqual(resp.content,'{"status": "success", "user": 1}') 
        self.user=User.objects.first()
        
    def test_regisit(self):
        data=self.data
        cl=Client(enforce_csrf_checks=True)
        cl.post('/user/regist',data=data)
        resp = cl.post('/user/regist',data=json.dumps(data),content_type='text/plain')
        self.assertEqual(resp.content,'{"status": "fail", "msg": "Car No has registed before"}')  
        data['car_no']='川B1234'
        resp = cl.post('/user/regist',data=json.dumps(data),content_type='text/plain')
        self.assertEqual(resp.content,'{"status": "fail", "msg": "Openid has been registed"}') 
        data['openid']='fff'
        resp = cl.post('/user/regist',data=json.dumps(data),content_type='text/plain')
        self.assertEqual(resp.content,'{"status": "fail", "msg": "Mobile Number has registed before"}')
    
    def test_login(self):
        cl=Client(enforce_csrf_checks=True)
        resp = cl.get('/user/login?openid=xxx')
        #self.assertEqual(resp.content,'{"status": "success", "data": {"uid": 1}}')
        dc =json.loads(resp.content)
        self.assertEqual(dc.get('uid'),1)
        resp =cl.get('/user/order/?user_session='+dc.get('user_session'))
        resp=cl.get('/user/login?mobile=17138080650&passwd=xxx')
        dc =json.loads(resp.content)
        self.assertEqual(dc.get('uid'),1)        
        
        resp=cl.get('/user/login?mobile=17138080650&passwd=xxxx')
        self.assertEqual(resp.content,'{"status": "fail", "msg": "password not right Or user not exist"}')
        
        resp=cl.get('/user/login?username=%s&passwd=xxx'%self.user.username)
        dc =json.loads(resp.content)
        self.assertEqual(dc.get('uid'),1)
    
    def test_del(self):
        cl=Client(enforce_csrf_checks=True)
        resp = cl.get('/user/del?openid=gg')
        print(resp.content)

class TestMeal(TestCase):
    def test_meal(self):
        MealModel.objects.create(name='single',label='测试套餐',org_price='10000',price='9800',\
                                 status='active',priority='100')
        MealModel.objects.create(name='single_02',label='测试套餐',org_price='10000',price='9800',\
                                status='active',priority='100')        
        cl=Client(enforce_csrf_checks=True)
        resp = cl.get('/meal')
        print(resp.content)
        

class TestBrand(TestCase):
    def test_brand(self):
        pass

class TestZk(TestCase):
    def setUp(self):
        CarWashLocalModel.objects.create(no='1234')
        
        CarBrandModel.objects.create(name='xxx')
        CarModelModel.objects.create(name='xxx')  
        
        self.cl=Client(enforce_csrf_checks=True)
        data={
            'mobile':'17138080650',
            'car_no':'川A1234',
            'nick':'我的昵称',
            'car_brand':'1',
            'car_model':'1',
            'passwd':'xxx',
            'openid':'xxx',
        }
        self.cl.post('/user/regist',data=json.dumps(data),content_type='application/json')
        
        
        
    def test_log(self):
        cl=Client(enforce_csrf_checks=True)
        resp = cl.get('/zk/log?code=e-134&zk=1234')
        self.assertEqual(ZKOtherLog.objects.count(),1)
        
        session=WashSessionModel.objects.create()
        resp= cl.get('/zk/washstate?state=jjyy&zk=1234&session=%s'%session.pk)
        self.assertEqual(ZKWashLog.objects.count(),1)
    
    def test_heart(self):
        cl=Client(enforce_csrf_checks=True)
        resp = cl.get('/zk/heartbeat?zk=1234')
        self.assertEqual(resp.content,'{"status": "success", "expire": 120}')
    
    def test_chepai_session(self):
        resp = self.cl.get('/zk/new_session?zk=dog')
        self.assertEqual(resp.content,'{"status": "fail", "msg": "zk number not registed"}')
        
        resp = self.cl.get('/zk/new_session?zk=1234&chepai=dog')
        self.assertEqual(resp.content,'{"status": "fail", "msg": "can not find match car"}')
        
        resp = self.cl.get('/zk/last_chepai?zk=1234')
        self.assertEqual(resp.content,'{"status": "success", "chepai": "dog"}')
        
        user=User.objects.get(pk=1)
        meal = MealModel.objects.create(name='single')
        OrderModel.objects.create(meal=meal,car=user.usercarmodel_set.first(),status='active')
        resp = self.cl.get('/zk/new_session?'+urllib.urlencode({'zk':'1234','chepai':b'川A1234'}))
        self.assertEqual(resp.content,'{"status": "success", "session": 1}')
    
    def test_qr_sesstion(self):
        user=User.objects.get(pk=1)
        meal = MealModel.objects.create(name='single',status='active')
        OrderModel.objects.create(meal=meal,car=user.usercarmodel_set.first(),status='active')  
        
        resp = self.cl.get('/user/login?openid=xxx')
        dc = json.loads(resp.content)
        self.assertEqual(dc.get('uid'),1)
        resp=self.cl.get('/user/order?view=qr')
        dc = json.loads(resp.content)
        qr_ul = urlparse.urlparse( dc.get('qr_url')).path
        resp = self.cl.get(qr_ul)
        # 变动的图片
        print(resp.content)
        
        resp = self.cl.get('/order/check_key?order_key=%s'%dc.get('key'))
        self.assertEqual( resp.content,'{"just_now_used": false, "status": "success"}')
        
        resp= self.cl.get('/zk/new_session?zk=1234&order_key=%s'%dc.get('key'))
        self.assertEqual(resp.content,'{"status": "success", "session": 1}')
        
        resp = self.cl.get('/order/check_key?order_key=%s'%dc.get('key'))
        self.assertEqual( resp.content,'{"just_now_used": true, "status": "success", "session": 1}')  
        
        resp= self.cl.get('/zk/new_session?zk=1234&order_key=%s'%dc.get('key'))
        self.assertEqual(resp.content,'{"status": "fail", "msg": "active order not exist or key has been expired"}')        
        
        self.cl.get('/session/check?session=213253')
    
    
class TestLocal(TestCase):
    def test_nearby(self):
        CarWashLocalModel.objects.create(no='1234',name='xxx',status='active',jd='104.266078',wd='30.602633')
        
        cl=Client(enforce_csrf_checks=True)
        resp = cl.get('/washlocal/nearby?jd=104.269078&wd=30.602633')
        self.assertEqual(resp.content,'{"status": "success", "locals": [{"jd": "104.266078", "wd": "30.602633", "name": "xxx"}]}')
    

class TestChepai(TestCase):
    def setUp(self):
        CarBrandModel.objects.create(name='xxx')
        CarModelModel.objects.create(name='xxx') 
        MealModel.objects.create(name='single',label='单次洗车',org_price='10000',price='1',\
                               status='active',priority='100') 
        cl=Client(enforce_csrf_checks=True)
        data={
            'mobile':'17138080650',
            'car_no':'川A1234',
            'nick':'我的昵称',
            'car_brand':'1',
            'car_model':'1',
            'passwd':'xxx',
            'openid':'xxx',
        }
        cl.post('/user/regist',data=json.dumps(data),content_type='application/json')     
        
    def test_chepai(self):
        """
        临时体验洗车，需要用户扫描二维码，前端轮询中控，获取当前车牌。
        前端利用该车牌，判断是否未注册，如果是，则可以请求生成single订单
        """
        cl=Client(enforce_csrf_checks=True)
        resp = cl.get('/car/anonymous_regist?chepai=川A33333')
        self.assertEqual(resp.content,'{"status": "success"}')
        # 多次注册应该都可以
        resp = cl.get('/car/anonymous_regist?chepai=川A33333')
        self.assertEqual(resp.content,'{"status": "success"}')        
        
        # 测试一下已经注册过的
        resp = cl.get('/car/anonymous_regist?chepai=川A1234')
        self.assertEqual(json.loads(resp.content).get('status'),'fail')
        
        #测试
        #resp = cl.get('/wxpay/new_order?pay_type=jsapi&openid=oIvmdwi8HWePf8rXFDA-jOpQL5uE&meal=single&chepai=川A33333')
        #print(resp.content)
    
    def test_chepai_session(self):
        cl=Client(enforce_csrf_checks=True)
        resp = cl.get('/block/car/active_session?chepai=川A33333')
        self.assertEqual(resp.content,'{"status": "fail", "msg": "please input registed chepai"}')
        
        resp = cl.get('/block/car/active_session?chepai=川A1234')
        self.assertEqual(resp.content,'{"status": "success", "session": null}')
        
        car = UserCarModel.objects.get(car_no='川A1234')
        wash1 = WashSessionModel.objects.create(car=car)
        ZKWashLog.objects.create(session=wash1,code=17002)
        resp = cl.get('/block/car/active_session?chepai=川A1234')
        self.assertEqual(resp.content,'{"status": "success", "session": null}')
        
        wash2 = WashSessionModel.objects.create(car=car)
        resp = cl.get('/block/car/active_session?chepai=川A1234')
        self.assertEqual(resp.content,'{"status": "success", "session": 2}')

        